using B.S.NewMedical.Api.Write.Application.Command.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Department
{
    /// <summary>
    /// 删除科室处理器
    /// 处理删除科室的业务逻辑，包括软删除等操作
    /// </summary>
    public class DeleteDepartmentsHandler : IRequestHandler<DeleteDepartmentsCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly ILogger<DeleteDepartmentsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// 注入依赖的服务
        /// </summary>
        /// <param name="departmentRepository">科室仓储接口</param>
        /// <param name="logger">日志记录器</param>
        public DeleteDepartmentsHandler(IBaseRepository<DepartmentModel> departmentRepository, ILogger<DeleteDepartmentsHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除科室命令
        /// 执行删除科室的业务逻辑（软删除）
        /// </summary>
        /// <param name="request">删除科室命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果，包含删除的科室ID</returns>
        public async Task<ApiResult<int>> Handle(DeleteDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理删除科室命令，科室ID: {DepartmentId}", request.Id);

                // 验证科室ID
                if (request.Id <= 0)
                {
                    _logger.LogWarning("科室ID无效: {DepartmentId}", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID无效"
                    };
                }

                // 检查科室是否存在
                var existingDepartment = _departmentRepository.GetAll()
                    .FirstOrDefault(d => d.Id == request.Id && !d.IsDeleted);
                
                if (existingDepartment == null)
                {
                    _logger.LogWarning("科室不存在或已被删除: {DepartmentId}", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = $"科室ID {request.Id} 不存在或已被删除"
                    };
                }

                // 检查是否有下级科室
                var hasSubDepartments = _departmentRepository.GetAll()
                    .Any(d => d.ParetId == request.Id && !d.IsDeleted);
                
                if (hasSubDepartments)
                {
                    _logger.LogWarning("科室存在下级科室，无法删除: {DepartmentId}", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "有下级科室，不能删"
                    };
                }

                // 软删除科室（设置删除标志）
                existingDepartment.IsDeleted = true;

                // 保存到数据库
                var result = await _departmentRepository.UpdateAsync(existingDepartment);

                _logger.LogInformation("科室删除成功，科室ID: {DepartmentId}, 科室名称: {DepartmentName}", 
                    request.Id, existingDepartment.DepartmentName);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "科室删除成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除科室时发生异常，科室ID: {DepartmentId}", request.Id);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = $"删除科室失败: {ex.Message}"
                };
            }
        }
    }
} 